package com.train.user.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.train.common.core.domain.entity.SysRole;
import com.train.common.core.domain.entity.SysUser;
import com.train.common.core.domain.model.LoginUser;
import com.train.common.utils.StringUtils;
import com.train.system.domain.SysUserRole;
import com.train.system.mapper.SysRoleMapper;
import com.train.system.mapper.SysUserMapper;
import com.train.system.mapper.SysUserRoleMapper;
import com.train.user.domain.UserWechat;
import com.train.user.domain.WechatAuth;
import com.train.user.mapper.WechatLoginMapper;
import com.train.user.service.WechatLoginService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;

@Service
public class WechatLoginServiceImpl implements WechatLoginService {

    @Autowired
    WechatLoginMapper wechatLoginMapper;

    @Autowired
    SysUserMapper sysUserMapper;

    @Autowired
    SysUserRoleMapper sysUserRoleMapper;

    @Autowired
    SysRoleMapper sysRoleMapper;


    @Transactional
    @Override
    public LoginUser wechatAuth(WechatAuth auth) {
        LambdaQueryWrapper<UserWechat> eq = new LambdaQueryWrapper<UserWechat>()
                .eq(UserWechat::getOpenid, auth.getOpenId());
        UserWechat userWechat = wechatLoginMapper.selectOne(eq);
        
        // 如果微信用户已存在，直接返回系统用户信息
        if (userWechat != null){
            SysUser sysUser = sysUserMapper.selectUserById(userWechat.getUserId());
            LoginUser loginUser = new LoginUser();
            loginUser.setUser(sysUser);
            loginUser.setUserId(sysUser.getUserId());
            List<SysRole> sysRoles = sysRoleMapper.selectRolesByUserName(sysUser.getUserName());
            HashSet<String> strings = new HashSet<>();
            for (SysRole sysRole : sysRoles) {
                strings.add(sysRole.getRoleKey());
            }
            loginUser.setPermissions(strings);

            return loginUser;
        } else {
            // 如果是新用户，创建系统用户并关联微信用户
            return createNewUserWithWechat(auth);
        }
    }
    
    /**
     * 为新微信用户创建系统用户并关联
     * @param auth 微信授权信息
     * @return 登录用户信息
     */
    private LoginUser createNewUserWithWechat(WechatAuth auth) {
        // 1. 创建系统用户
        SysUser sysUser = new SysUser();
        sysUser.setUserName(generateRandomUsername());
        sysUser.setNickName("微信用户" + generateRandomNicknameSuffix());
        sysUser.setStatus("0"); // 正常状态
        sysUser.setDelFlag("0"); // 未删除
        sysUser.setCreateBy("wechat");
        sysUser.setCreateTime(new Date());
        
        // 2. 插入系统用户
        sysUserMapper.insertUser(sysUser);
        
        // 3. 为用户分配普通用户角色（角色ID为2）
        SysUserRole userRole = new SysUserRole();
        userRole.setUserId(sysUser.getUserId());
        userRole.setRoleId(2L);
        sysUserRoleMapper.batchUserRole(Arrays.asList(userRole));
        
        // 4. 创建微信用户关联记录
        UserWechat userWechat = new UserWechat();
        userWechat.setOpenid(auth.getOpenId());
        userWechat.setUnionid(auth.getUnionId());
        userWechat.setUserId(sysUser.getUserId());
        userWechat.setNickname(sysUser.getNickName());
        userWechat.setDelFlag("0");
        // 5. 插入微信用户关联记录
        wechatLoginMapper.insert(userWechat);
        
        // 6. 返回登录用户信息
        LoginUser loginUser = new LoginUser();

        loginUser.setUser(sysUser);

        BeanUtils.copyProperties(sysUser, loginUser);
        System.out.println(loginUser.getUsername());
        return loginUser;
    }
    
    /**
     * 生成随机用户名
     * @return 随机用户名
     */
    private String generateRandomUsername() {
        String prefix = "user_";
        String randomStr = UUID.randomUUID().toString().substring(0, 8);
        String username = prefix + randomStr;
        
        // 检查用户名是否已存在，如果存在则重新生成
        while (sysUserMapper.checkUserNameUnique(username) != null) {
            randomStr = UUID.randomUUID().toString().substring(0, 8);
            username = prefix + randomStr;
        }
        
        return username;
    }
    
    /**
     * 生成随机昵称后缀
     * @return 随机昵称后缀
     */
    private String generateRandomNicknameSuffix() {
        Random random = new Random();
        return String.valueOf(10000 + random.nextInt(90000)); // 生成5位随机数
    }
}